package com.fjwt.gz.service.activity.coupon.notify;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.coupon.wx.WxCouponWriteNotifyService;
import com.fjwt.gz.db.entity.AwardCouponNotifyEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.entity.PayOrderEntity;
import com.fjwt.gz.interfaces.ChannelCouponWriteService;
import com.fjwt.gz.service.impl.AwardCouponNotifyService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.PayOrderService;
import com.fjwt.gz.service.impl.ScoreRecordTotalService;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.wx.IWxConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 小邮付的支付公众号配置的卡券核销处理逻辑
 **/

@Service
@Slf4j
public class WxCouponWriteService implements ChannelCouponWriteService {

    @Autowired
    private AwardCouponNotifyService awardCouponNotifyService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ScoreRecordTotalService scoreRecordService;
    @Autowired
    private WxCouponWriteNotifyService wxCouponWriteNotifyService;

    @Autowired
    private IWxConfigService wxConfigService;

    private static String logPrefix = "微信卡券核销回调";

    @Override
    public void couponDoNotice(AwardCouponNotifyEntity couponNotifyEntity) throws Exception {
        log.info(logPrefix + "处理逻辑进来的参数是：{}", JSONUtil.toJsonStr(couponNotifyEntity));
        //通过卡券三方id是否存在，如不存在，更新回调记录表，添加备注
        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponNotifyEntity.getCouponThirdId());
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);

        if (ObjectUtil.isNotEmpty(fansAwardEntity)) {
            if (fansAwardEntity.getState() == 1) {
                //卡券不是英雄啊平台创建
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("此订单已经推送过");
                log.info(logPrefix + "处理逻辑,此卡券此订单已经推送过,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            } else {
                // 处理卡券核销是否进行奖励积分
                scoreRecordService.couponWriteSendScore(fansAwardEntity);
                //是卡券营销平台创建,卡券核销后的处理
                log.info(logPrefix + "extraJson:{}", fansAwardEntity.getExtraJson());
                JSONObject extraJson = JSONObject.parseObject(fansAwardEntity.getExtraJson());
                if (extraJson != null) {
                    String templateNo = extraJson.getString("templateNo");
                    BaseActivityService activityService = SpringBeansUtil.getBean(templateNo + "Service", BaseActivityService.class);
                    // 支付通道接口实现类存在走对应的run方法
                    if (activityService != null) {
                        JSONObject json = JSONObject.parseObject(JSONUtil.toJsonStr(fansAwardEntity));
                        log.info(templateNo + "Service,接口存在,走对应的run方法，开始进入run方法，进去的信息是:{}", JSONUtil.toJsonStr(json));
                        activityService.run(json);
                    }

                    FansAwardEntity fansAwardEntityUpdate = new FansAwardEntity();
                    fansAwardEntityUpdate.setFansAwardId(fansAwardEntity.getFansAwardId());
                    fansAwardEntityUpdate.setState(1);
                    //使用三方的核销时间
                    JSONObject notifyJson = JSONObject.parseObject(couponNotifyEntity.getNotifyJson());
                    JSONObject consumeInformation = JSONObject.parseObject(notifyJson.getString("consume_information"));
                    fansAwardEntityUpdate.setWriteTime(DateUtil.parse(consumeInformation.getString("consume_time")));

                    //如果能通过三方卡券id查询到订单，则添加商户号，（此订单核销属于新平台的订单，如果没有则表示是老平台的订单，就没有商户号）
                    LambdaQueryWrapper<PayOrderEntity> payOrderGw = PayOrderEntity.gw();
                    payOrderGw.eq(PayOrderEntity::getCouponThirdId, fansAwardEntity.getCouponThirdId());
                    PayOrderEntity payOrderEntity = payOrderService.getBaseMapper().selectOne(payOrderGw);
                    if (ObjectUtil.isNotEmpty(payOrderEntity)) {
                        fansAwardEntityUpdate.setMchNo(payOrderEntity.getMchNo());
                    }
                    log.info(logPrefix + "此卡券核销更新数据，更新数据的信息是：{}", JSONUtil.toJsonStr(fansAwardEntityUpdate));
                    fansAwardService.updateById(fansAwardEntityUpdate);

                    //更新回调数据状态
                    AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                    couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                    couponNotifyUpdate.setState(2);
                    couponNotifyUpdate.setRemark("核销成功");
                    log.info(logPrefix + "核销成功,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                    awardCouponNotifyService.updateById(couponNotifyUpdate);
                } else {
                    FansAwardEntity fansAwardEntityUpdate = new FansAwardEntity();
                    fansAwardEntityUpdate.setFansAwardId(fansAwardEntity.getFansAwardId());
                    fansAwardEntityUpdate.setState(1);
                    fansAwardEntityUpdate.setWriteTime(new Date());
                    //如果能通过三方卡券id查询到订单，则添加商户号，（此订单核销属于新平台的订单，如果没有则表示是老平台的订单，就没有商户号）
                    LambdaQueryWrapper<PayOrderEntity> payOrderGw = PayOrderEntity.gw();
                    payOrderGw.eq(PayOrderEntity::getCouponThirdId, fansAwardEntity.getCouponThirdId());
                    PayOrderEntity payOrderEntity = payOrderService.getBaseMapper().selectOne(payOrderGw);
                    if (ObjectUtil.isNotEmpty(payOrderEntity)) {
                        fansAwardEntityUpdate.setMchNo(payOrderEntity.getMchNo());
                    }
                    log.info(logPrefix + "此卡券核销无核销后的处理逻辑，更新数据的信息是：{}", JSONUtil.toJsonStr(fansAwardEntityUpdate));
                    fansAwardService.updateById(fansAwardEntityUpdate);
                }
            }
        } else {
            //卡券不是英雄啊平台创建
            AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
            couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
            couponNotifyUpdate.setState(2);
            couponNotifyUpdate.setRemark("此卡券不是营销平台创建");
            log.info(logPrefix + "处理逻辑,此卡券不是营销平台创建,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
            awardCouponNotifyService.updateById(couponNotifyUpdate);
        }
    }

    @Override
    public String addNotifyRecord(Map<String, Object> requestMap) {
        JSONObject respJson = new JSONObject();
        log.info(logPrefix + "添加回调信息记录进来的参数是：{}", JSONUtil.toJsonStr(requestMap));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.TEXT_HTML);
        AwardCouponNotifyEntity couponNotifyEntity = new AwardCouponNotifyEntity();
        Date date = new Date();

        String status = MapUtil.getStr(requestMap, "status");
        log.info(logPrefix + "status：{}", status);
        // 微信状态对应的notify_state ： SENDED：可用 --->  1未核销;  USED：已实扣 ---> 0：已核销 ; EXPIRED：已过期  ---->  2已过期
        if ("USED".equals(status)) {
            couponNotifyEntity.setNotifyState(0);
        } else if ("EXPIRED".equals(status)) {
            couponNotifyEntity.setNotifyState(2);
        } else {
            couponNotifyEntity.setNotifyState(1);
        }
        String couponThirdId = MapUtil.getStr(requestMap, "coupon_id");


        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponThirdId);
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);
        if (ObjectUtil.isEmpty(fansAwardEntity)) {
            log.info("卡券ID：{}，此卡券不是营销平台创建，直接返回，不记录数据库", couponThirdId);
            respJson.put("code", 500);
            respJson.put("msg", "此卡券不是营销平台创建，直接返回");
            respJson.put("data", "");
            return JSONUtil.toJsonStr(ApiRes.fail(ApiCodeEnum.SYS_WXCOUPON_FAIL_NOTIFY));
        }

        couponNotifyEntity.setCouponThirdId(couponThirdId);
        couponNotifyEntity.setIfcode("wx");
        couponNotifyEntity.setState(1);//回调进来的都是状态1未同步
        couponNotifyEntity.setNotifyJson(JSONUtil.toJsonStr(requestMap));
        couponNotifyEntity.setCreatedAt(date);
        couponNotifyEntity.setUpdatedAt(date);
        couponNotifyEntity.setSourceType(1);
        log.info(logPrefix + "添加回调信息记录:{}", JSONUtil.toJsonStr(couponNotifyEntity));
        boolean save = awardCouponNotifyService.save(couponNotifyEntity);
        if (save == true) {
            respJson.put("code", 200);
            respJson.put("msg", "SUCCESS");
            respJson.put("data", "");
            return JSONUtil.toJsonStr(ApiRes.fail(ApiCodeEnum.SYS_WXCOUPON_SUCCESS_NOTIFY));
        } else {
            respJson.put("code", 500);
            respJson.put("msg", "FAIL");
            respJson.put("data", "回调失败");
            return JSONUtil.toJsonStr(ApiRes.fail(ApiCodeEnum.SYS_WXCOUPON_FAIL_NOTIFY));
        }
    }

    /**
     * 解析参数
     **/
    @Override
    public Map<String, Object> paraseParamters(HttpServletRequest request) throws IOException {
        return wxCouponWriteNotifyService.paraseParamters(request,wxConfigService.getNotificationConfig());
    }
}
